# -*- coding: utf-8 -*-            
# @Author : HJH
# @Time : 2024/3/2 10:43
# @Use :
import json
import time

import openpyxl
import requests


def send_request(tfstk, m_h5_tk, m_h5_tk_enc, isg, t, sign):
    headers = {
        "authority": "h5api.m.taobao.com",
        "accept": "application/json",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "b-fpt": "pageStrategyId(37)index_type(new)",
        "content-type": "application/x-www-form-urlencoded",
        "origin": "https://outfliggys.m.taobao.com",
        "referer": "https://outfliggys.m.taobao.com/",
        "sec-ch-ua": "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Microsoft Edge\";v=\"122\"",
        "sec-ch-ua-mobile": "?1",
        "sec-ch-ua-platform": "\"Android\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36 Edg/122.0.0.0",
        "warehousecode": "{\"clientType\":\"other\",\"os\":\"android\",\"osVersion\":\"6.0\",\"appVersion\":\"\",\"containerVersion\":\"0.0.0\",\"pageType\":\"h5\",\"ttid\":\"700169@travel_android_9.9.73.104\",\"spm\":\"181.28951085\",\"spmUrl\":\"181.7437856.activity.2_hangsizhuanqu\",\"spmPre\":\"\",\"fpt\":\"pageStrategyId(37)index_type(new)\"}"
    }
    cookies = {
        "WAPFDFDTGFG": "%2B4cMKKP%2B8PI%2BKK8fqXyEfp9MM7xypw%3D%3D",
        "_w_app_lg": "0",
        "thw": "cn",
        "_fli_titleHeight": "0",
        "t": "921bbac4ecf82be982d8f7d7d6b63b34",
        "_fli_screenDix": "0.40540540540540543",
        "mt": "ci=0_0",
        "3PcFlag": "1709367266239",
        "cna": "K0TeHWtLhxMCAQAAAAAMLBd0",
        "sgcookie": "E100zKoTlosH4EZasND0RK325N1415vIrrHPBinUP7RZoh9O2tGEyrhZ%2FF5Egw5UZpppcMzcWLV0kENj3zxklDB%2BUQvdmG1idFP3HSWd%2FylcreLkAdu85ALNLC2JHKEqbWum",
        "uc3": "lg2=URm48syIIVrSKA%3D%3D&vt3=F8dD3erxD24YW%2FXPg3E%3D&id2=UUpgQyuGd6J2vD4Ppg%3D%3D&nk2=qiAr7EqCkGqAQSZY",
        "lgc": "%5Cu4E0A%5Cu6D77%5Cu6613%5Cu5B89%5Cu822A%5Cu670D",
        "uc4": "nk4=0%40qBqkhdwDS7Zr4DcDOUTQPjj18It4whM%3D&id4=0%40U2gqzJ06j3C1pmDnQ1iSFrpuxAV6I%2BED",
        "tracknick": "%5Cu4E0A%5Cu6D77%5Cu6613%5Cu5B89%5Cu822A%5Cu670D",
        "_cc_": "WqG3DMC9EA%3D%3D",
        "_samesite_flag_": "true",
        "cookie2": "168a3c0bb94766bae50b71fd1d11e95f",
        "_tb_token_": "e573be6ebebe8",
        "tfstk": tfstk,
        "mtop_partitioned_detect": "1",
        "_m_h5_tk": m_h5_tk,
        "_m_h5_tk_enc": m_h5_tk_enc,
        "isg": isg
    }
    url = "https://h5api.m.taobao.com/h5/mtop.trip.flight.cp.rule.promoton/1.0"
    params = {
        "type": "originaljson",
        "api": "mtop.trip.flight.cp.rule.promoton",
        "v": "1.0",
        "ttid": "700169@travel_android_9.9.73.104",
        "appKey": "12574478",
        "t": t,
        "sign": sign
    }
    data = {
        "data": "{\"queryCount\":12,\"ruleId\":426474}"
    }
    response = requests.post(url, headers=headers, cookies=cookies, params=params, data=data)
    return json.loads(response.text)


if __name__ == '__main__':
    i_tfstk = input("请输入tfstk: ")
    i_m_h5_tk = input("请输入m_h5_tk: ")
    i_m_h5_tk_enc = input("请输入m_h5_tk_enc: ")
    i_isg = input("请输入isg: ")
    i_t = input("请输入t: ")
    i_sign = input("请输入sign: ")

    price_list = []
    count = 1
    while True and count <= 600:
        try:
            print(f"第{count}次请求... ...")
            res_data = send_request(i_tfstk, i_m_h5_tk, i_m_h5_tk_enc, i_isg, i_t, i_sign)
            print(f"请求结果{res_data['ret'][0]}")
            for item in res_data['data']['cheapFlights']:
                price_list.append(item)
        except Exception as e:
            print(e)
        time.sleep(3)
        count = count + 1

    # 使用一个集合来存储已经出现过的 '到达-起飞-起飞日期' 组合
    seen_combinations = set()

    # 用于存储去重后的结果
    deduped_price_list = []

    for item in price_list:
        combination = (item['arrCityName'], item['depCityName'], item['depDate'])
        # 如果组合没有出现过，则加入到结果列表，并标记已经出现
        if combination not in seen_combinations:
            deduped_price_list.append(item)
            seen_combinations.add(combination)

    # 创建一个新的 Excel 工作簿
    wb = openpyxl.Workbook()
    ws = wb.active

    # 设置表头
    headers = ['到达', '起飞', '起飞日期', '星期', '直飞', '价格', '链接']
    header_mapping = {'到达': 'arrCityName', '起飞': 'depCityName', '起飞日期': 'depDate', '星期': 'depWeek',
                      '直飞': 'direct', '价格': 'price', '链接': 'defaultJumpURL'}
    for idx, header in enumerate(headers, start=1):
        ws.cell(row=1, column=idx, value=header)

    # 将数据根据字段对应到指定表头列
    for row_idx, row_data in enumerate(deduped_price_list, start=2):
        for col_idx, header in enumerate(headers, start=1):
            key = header_mapping.get(header)
            cell_value = row_data.get(key, '')
            ws.cell(row=row_idx, column=col_idx, value=cell_value)

    # 保存 Excel 文件
    wb.save('飞猪航司好价.xlsx')
